<template>
    <div>
        <el-dialog
            v-model="dialogVisible"
            title="添加店铺"
            width="500px"
            :close-on-click-modal="false"
        >
            <el-form
                ref="formRef"
                :model="form"
                :rules="rules"
                label-width="80px"
                label-position="right"
            >
                <el-form-item label="店铺名称" prop="name" class="mb-10">
                    <el-input v-model="form.name" placeholder="请输入店铺名称" />
                </el-form-item>

                <el-form-item label="店铺图片" prop="image">
                    <el-upload
                        class="shop-image-uploader"
                        :show-file-list="false"
                        :auto-upload="false"
                        accept="image/*"
                        :on-change="handleImageChange"
                    >
                        <img v-if="imageUrl" :src="imageUrl" class="shop-image" />
                        <el-icon v-else class="shop-image-uploader-icon"><Plus /></el-icon>
                    </el-upload>
                    <div class="image-tip">建议尺寸：360x250px，支持jpg、png格式</div>
                </el-form-item>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" :loading="loading" @click="submitForm">确认</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import type { FormInstance, FormRules, UploadFile } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import instance from '@/api'

const dialogVisible = ref(false)
const formRef = ref<FormInstance>()
const imageUrl = ref('')
const imageFile = ref<File>()
const loading = ref(false)

const form = reactive({
    name: '',
    image: ''
})

const rules = reactive<FormRules>({
    name: [
        { required: true, message: '请输入店铺名称', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    image: [
        { required: true, message: '请上传店铺图片', trigger: 'change' }
    ]
})

const handleImageChange = (file: UploadFile) => {
    // 验证文件类型
    const isImage = file.raw?.type.startsWith('image/')
    if (!isImage) {
        ElMessage.error('只能上传图片文件！')
        return
    }

    // 验证文件大小（限制为2MB）
    const isLt2M = file.size! / 1024 / 1024 < 2
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB!')
        return
    }

    // 保存文件对象和预览URL
    imageFile.value = file.raw
    imageUrl.value = URL.createObjectURL(file.raw!)
    form.image = file.name
}

const submitForm = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid) => {
        if (valid) {
            loading.value = true
            try {
                // 创建 FormData 对象上传文件
                const formData = new FormData()
                formData.append('shopName', form.name)
                if (imageFile.value) {
                    formData.append('file', imageFile.value)
                }

                // 调用API上传数据
                const resp = await instance.post('/api/shop/uploadShop', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                })
                // 触发父组件的添加事件
                emit('shop-added', {
                    id: resp.data.id,
                    name: resp.data.shop_name,
                    image: resp.data.shop_url
                })

                // 关闭弹窗并重置表单
                dialogVisible.value = false
                if (formRef.value) {
                    formRef.value.resetFields()
                }
                imageUrl.value = ''
                imageFile.value = undefined
                ElMessage.success('添加店铺成功')
            } catch (error) {
                console.error('上传失败:', error)
                ElMessage.error('上传失败，请检查网络连接')
            } finally {
                loading.value = false
            }
        }
    })
}

// 定义事件
const emit = defineEmits<{
    (e: 'shop-added', shop: { id: number, name: string, image: string }): void
}>()

// 暴露方法给父组件调用
defineExpose({
    show: () => {
        dialogVisible.value = true
    }
})

</script>

<style scoped>
.shop-image-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color 0.3s;
}

.shop-image-uploader:hover {
    border-color: #409EFF;
}

.shop-image-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 200px;
    height: 150px;
    text-align: center;
    line-height: 150px;
}

.shop-image {
    width: 200px;
    height: 150px;
    display: block;
    object-fit: cover;
}

.image-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 8px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}
</style>